package org.azj.dbOperatorComponent;

import java.io.File;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ImageBlobStrategy implements IDealBlobStrategy{

	java.io.BufferedInputStream imageInput;
	String fileNameString;
	
	@Override
	public PreparedStatement dealBlob(
			PreparedStatement preparedStatement, 
			int index,
			String content) throws SQLException{
		
		try {
			// in this case, content is the full path of img file
			fileNameString = content;
			File file = new File(content);
			imageInput = 
					new java.io.BufferedInputStream(new java.io.FileInputStream(file));
			preparedStatement.setBinaryStream(
					index, imageInput,(int) file.length());	
			
			return preparedStatement;
		} catch (Exception e) {
			throw new SQLException(
					"BLOB数据转换出现错误，期望的样式是已存在文件的文件名，但是检查该路径不是文件或者文件不存在"
					+ "当前文件名是[" + content + "]");
		}
	}
	
	@Override
	public void close() throws SQLException{
		try {
			if (imageInput != null) {
				imageInput.close();	
			}	
		} catch (Exception e) {
			throw new SQLException(
					"BLOB数据转换出现错误，关闭图像文件[" + fileNameString + "]时发生异常");
		}
	}
	
}
